import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation';
import { Platform, ToastController, AlertController, LoadingController, Loading, ModalController } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { Diagnostic } from '@ionic-native/diagnostic';
import { Toast } from '@ionic-native/toast';
/*
  Generated class for the NativeServiceProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
declare var BMap;
declare var baidu_location;
@Injectable()
export class NativeServiceProvider {
  options = {
    maximumAge: 3600000,
    timeout: 3000,
    enableHighAccuracy: true,
  }
  lat:number=-1;
  lon:number=-1;
  loading: Loading;

  private msg="init";
  getmsg(){return this.msg;}
  constructor(
    //public http: HttpClient,
    private geolocation: Geolocation,
    public platform: Platform, public diagnostic: Diagnostic,
    public alertCtrl: AlertController,
public loadingCtrl: LoadingController,
public toast: Toast,
public toastCtrl: ToastController,
    ) {
    console.log('Hello NativeServiceProvider Provider');
  }


  hideLoading(): void {

    //判断是否正在显示
    if (this.loading != null) this.loading.dismiss();
  };

    /**
   * 如果是真机环境，调用原生toast，否则调用自带的ToastController来显示。
   * @param message 信息内容
   * @param duration 显示时长(默认2000)
   * @param position 显示位置(默认为bottom)，还可以为top和middle(或center)
   */
  showToast(message: string = '完成', duration: number = 1500, position = "bottom"): void {
    if (this.isMobile()) {
      //注意show()方法返回的是observable，而且一定要调用subscribe才会显示
      //原生toast显示位置为top、center、bottom
      if (position == 'middle') this.toast.show(message, String(duration), 'center').subscribe();
      else this.toast.show(message, String(duration), position).subscribe();
    } else {
      if (position == 'center') {
        this.toastCtrl.create({
          message: message,
          duration: duration,
          position: 'middle',
          showCloseButton: false   //是否在toast中显示一个关闭按钮
        }).present();
      }
      else {
        this.toastCtrl.create({
          message: message,
          duration: duration,
          position: position,
          showCloseButton: false   //是否在toast中显示一个关闭按钮
        }).present();
      }
    }
  };
  //是否有定位授权
  public locationPermissionsAuthorization = (() => {

    let havePermission = false;
    return () => {
      return Observable.create(observer => {
        this.msg="11";
        if (havePermission) {
          this.msg="22";
          observer.next(true);
        } else {
          this.msg="33";
          if (!this.isIos()) {
            console.log('android device')
            this.msg="55";
            let permissions = [this.diagnostic.permission.ACCESS_FINE_LOCATION, this.diagnostic.permission.ACCESS_COARSE_LOCATION, this.diagnostic.permission.WRITE_EXTERNAL_STORAGE, this.diagnostic.permission.READ_EXTERNAL_STORAGE];
            console.log('permissions finished')
            this.diagnostic.getPermissionsAuthorizationStatus(permissions).then(res => {
              this.msg="66";
              if (res.ACCESS_FINE_LOCATION == 'GRANTED' && res.ACCESS_COARSE_LOCATION == 'GRANTED' && res.WRITE_EXTERNAL_STORAGE == 'GRANTED' && res.READ_EXTERNAL_STORAGE == 'GRANTED') {
                havePermission = true;
                this.msg="77";
                observer.next(true);
              } else {
                this.msg="88";
                havePermission = false;
                this.diagnostic.requestRuntimePermissions(permissions).then(res => {//请求权限
                  if (res.ACCESS_FINE_LOCATION == 'GRANTED' && res.ACCESS_COARSE_LOCATION == 'GRANTED' && res.WRITE_EXTERNAL_STORAGE == 'GRANTED' && res.READ_EXTERNAL_STORAGE == 'GRANTED') {
                    havePermission = true;
                    observer.next(true);
                  } else {
                    havePermission = false;
                    this.alertCtrl.create({
                      title: '缺少定位和读取SD卡权限',
                      subTitle: '请在手机设置或app权限管理中开启',
                      buttons: [{ text: '取消' },
                      {
                        text: '去开启',
                        handler: () => {
                          this.diagnostic.switchToSettings();
                        }
                      }
                      ]
                    }).present();
                  }
                }).catch(err => {
                  console.log(err, '调用diagnostic的请求定位权限方法失败1');
                });
              }
            }).catch(err => {
              console.log(err, '调用diagnosticc的请求定位权限方法失败2');
            });
          } else {//ios
            this.msg="44";
            this.diagnostic.getLocationAuthorizationStatus().then(
              (status) => {
                this.msg="55";
                if (status === this.diagnostic.permissionStatus.GRANTED || status === this.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE) {
                  havePermission = true;
                  observer.next(true);
                } else {
                  this.diagnostic.requestLocationAuthorization().then(
                    (status) => {
                      if (status == this.diagnostic.permissionStatus.GRANTED || status == this.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE) {
                        havePermission = true;
                        observer.next(true);
                      } else {
                        this.alertCtrl.create({
                          title: '缺少定位权限',
                          subTitle: '请在手机设置或app权限管理中开启',
                          buttons: [{ text: '取消' },
                          {
                            text: '去开启',
                            handler: () => {
                              this.diagnostic.switchToSettings();
                            }
                          }
                          ]
                        }).present();
                      }
                    }
                  )
                }

              });
          }
        }
      });
    };
  })();


  isMobile(): boolean {
    //mobile包括android、ios、ipad等，mobileweb是在真机上的浏览器中
    return this.platform.is('mobile') && !this.platform.is('mobileweb');
  }

  isIos(): boolean {
    return this.isMobile() && (this.platform.is('ios') || this.platform.is('ipad') || this.platform.is('iphone'));
  }
    //返回当前经纬度
    getCurrentPosition(): Promise<any> {
      return new Promise<any>(
        (resolve, reject) => {
          if (this.isIos()) {
            this.geolocation.getCurrentPosition({ timeout: 5000,
              enableHighAccuracy: true }).then((res) => {
              let lat = res.coords.latitude;
              let lon = res.coords.longitude;
              var convertor = new BMap.Convertor();
              var pointArr = [];
              let mpoint = new BMap.Point(lon, lat);
              pointArr.push(mpoint);
              convertor.translate(pointArr, 1, 5, (data) => {
                if (data.status === 0) {
                  this.lat = data.points[0].lat;
                  this.lon = data.points[0].lng;
                }
              });
              //console.log('location',res, 'convert to', this.global.lat, this.global.lon);
              resolve({ lat: res.coords.latitude, lon: res.coords.longitude });
            }).catch((error) => {
              reject(error);
            })
          } else {
            this.locationPermissionsAuthorization().subscribe((hasPermission) => {
              console.log("是否获取到权限 " + hasPermission);
              if (hasPermission == true) {
                this.platform.ready().then(() => {
                  console.log("开始定位");
                  if (typeof baidu_location === "undefined") {
                    alert("baidu_location is undefined");
                    reject("baidu_location未定义");
                  };
                  baidu_location.getCurrentPosition((data) => {
                    if (data.locType == 161) {
                      this.lat = data.latitude;
                      this.lon = data.longitude;
                      resolve({ lat: data.latitude, lon: data.longitude })
                    } else {
                      reject(JSON.stringify(data));
                    }
                  }, (error) => {
                    reject(JSON.stringify(error));
                  });
                })
              } else {
                reject("没有开启定位权限");
              }
            })
          }

        }
      );
    }

    getCurrentPositionfromBaidyu(): Promise<any> {
      return new Promise<any>(
        (resolve, reject) => {
          this.msg=("开始获取位置");
            this.locationPermissionsAuthorization().subscribe((hasPermission) => {

              if (hasPermission) { //hasPermission == true
                this.platform.ready().then(() => {
                  console.log("开始定位");
                  this.msg=("开始定位");
                  if (typeof baidu_location === "undefined") {
                    //alert("baidu_location is undefined");
                    this.msg=("baidu_location is undefined");
                    reject("baidu_location未定义");
                  };
                  baidu_location.getCurrentPosition((data) => {
                    this.msg=("data:"+JSON.stringify(data));
                    if (data.locType == 161) {
                      this.lat = data.latitude;
                      this.lon = data.longitude;
                      resolve({ lat: data.latitude, lon: data.longitude })
                    } else {
                      this.msg=("data:"+JSON.stringify(data));
                      reject(JSON.stringify(data));
                    }
                  }, (error) => {
                    this.msg=("data:"+JSON.stringify(error));
                    reject(JSON.stringify(error));
                  });
                })
              } else {
                this.msg=("没有开启定位权限");
                reject("没有开启定位权限");
              }
           })
        }
      );
    }
}
